package com.herui.ota.utils;

import com.alibaba.fastjson.JSON;
import com.herui.ota.exception.ServiceException;
import com.mlnx.common.entity.Response;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: Akrio
 * @Date: 2021/4/7 13:11
 */
public class DownloadUtil {

    public static void downloadFile(String filePath, String fileName, HttpServletResponse response) throws IOException {
        // 设置响应的Header参数
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

        // 读取文件内容并将其转换为字节数组
        FileInputStream fis = new FileInputStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] buffer = new byte[bis.available()];
        bis.read(buffer);

        // 设置文件的MIME类型
        response.setContentType("application/octet-stream");

        // 设置响应的Content-Disposition头部信息
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        // 将字节数组写入响应的输出流
        OutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);
        bos.write(buffer);
        bos.flush();

        // 关闭输出流
        bos.close();
        bis.close();
    }
    public static void downloadExcel(HttpServletResponse response, byte[] bytes) {
        // response.reset();
        // String fileName = new String("奥迪".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" + "Excel.xls");
        response.setContentLength((bytes.length));
        try {
            OutputStream os = response.getOutputStream();
            os.write(bytes, 0, bytes.length);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void downloadExcel(HttpServletResponse response, byte[] bytes, String fileName) {
        // response.reset();
        // String fileName = new String("奥迪".getBytes(), StandardCharsets.ISO_8859_1);

        try {
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.setContentLength((bytes.length));
            OutputStream os = response.getOutputStream();
            os.write(bytes, 0, bytes.length);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    public static byte[] file2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static void downloadTxt(HttpServletResponse response, String str) {
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition.txt", "attachment;fileName=" + "Error.txt");

        response.setContentLength((str.getBytes().length));
        try {
            OutputStream os = response.getOutputStream();
            os.write(str.getBytes(), 0, str.getBytes().length);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // response.setContentLength((str.getBytes().length));
        // try {
        // PrintWriter writer = response.getWriter();
        // writer.print(str);
        // writer.close();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
    }

    public static void sendJson(HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        Response result = new Response();
        try {
            PrintWriter writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendHTML(HttpServletResponse response, String str) {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentLength((str.getBytes().length));
        try {
            PrintWriter writer = response.getWriter();
            writer.print(str);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveExcel(MultipartFile file) {
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName1 = null;
        try {
            inputStream = file.getInputStream();
            fileName1 = file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String path = "excel";
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            assert fileName1 != null;
            String[] fileName = fileName1.split("\\\\");
            os = new FileOutputStream(
                tempFile.getPath() + File.separator + format.format(new Date()) + fileName[fileName.length - 1]);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String saveFile(MultipartFile file) {
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName1 = null;
        String name = null;
        try {
            inputStream = file.getInputStream();
            fileName1 = file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String path = "file";
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            assert fileName1 != null;
            String[] fileName = fileName1.split("\\\\");
            name = tempFile.getPath() + File.separator + fileName[fileName.length - 1];
            os = new FileOutputStream(name);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return name;
    }

    public static String saveFile2(MultipartFile file) {
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName1 = null;
        String name = null;
        String filen = null;
        try {
            inputStream = file.getInputStream();
            fileName1 = file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String path = "E:\\file";
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            assert fileName1 != null;
            String[] fileName = fileName1.split("\\\\");
            name = tempFile.getPath() + File.separator + fileName[fileName.length - 1];
            filen = fileName[fileName.length - 1];
            os = new FileOutputStream(name);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String s = "^[^+/?%#&=]+$";
        if (!filen.matches(s))
            throw new ServiceException("文件名称不能包含+/?%#&=特殊字符");
        return filen;
    }

    /**
     * @param file
     * @return 服务器地址+存储文件名称
     */
    public static String saveFile3(MultipartFile file) {
        // try {
        // InetAddress localHost = InetAddress.getLocalHost();
        // return "http://" + localHost.getHostAddress() + ":9091/uploading/download?fileName=" + saveFile2(file);
        // } catch (UnknownHostException e) {
        // e.printStackTrace();
        // }
        return "http://10.70.21.15:9091/uploading/download?fileName=" + saveFile2(file);
    }




    // public static String saveFile2(MultipartFile file) {
    // try {
    // InetAddress localHost = InetAddress.getLocalHost();
    // return "http://"+localHost.getHostAddress()+":9091/uploading/download?fileName="+saveFile(file);
    // } catch (UnknownHostException e) {
    // e.printStackTrace();
    // }
    // return null;
    // }

//    public static void main(String[] args) {
//        try {
//            compressFile("file/物模型.xls", "file/物模型.zip");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
